App({
	config: {'fromw7':true,"tabBarUrls":[]},aid:0,mid:0,needAuth:0,tabBarData:false,platform:'wx',indexurl:'/pages/index/index',textset:[],
	onLaunch:function(options){
		console.log('onLaunch')
		var extConfig = wx.getExtConfigSync? wx.getExtConfigSync(): {}
		if (extConfig && extConfig.aid){
			this.config.baseurl = extConfig.baseurl;
			this.config.aid = extConfig.aid;
			this.pre_url = this.config.baseurl;
			this.config.baseurl = this.config.baseurl + '/m.php?s=/';
		}else{
			this.config.aid = this.siteInfo.uniacid;
			var siteroot = this.siteInfo.siteroot
			this.pre_url = siteroot;
			this.config.baseurl = siteroot + '/m.php?s=/';
		}
		this.aid = this.config.aid;
	},
	onShow: function (options) {
		console.log('onShow')
		this.config.session_id = wx.getStorageSync('session_id');
		this.reguser(options.query, function () { })
	},
	inArray: function (search, array) {
		for (var i in array) {
			if (array[i] == search) {
				return true;
			}
		}
		return false;
	},
	isNull: function (e) {
		return e == undefined || e == "undefined" || e == null || e == ""
	},
	parseJSON: function (e) {
		try {
			return JSON.parse(e)
		} catch (t) {
			return undefined
		}
	},
	getpage: function () {
		var pages = getCurrentPages();
		return pages[pages.length - 1];
	},
	alert: function (content, confirmfun) {
		wx.showModal({
			title: '提示信息',
			showCancel: false,
			content: content.toString(),
			success: function (res) {
				if (res.confirm) {
					typeof confirmfun == 'function' && confirmfun();
				}
			}
		});
	},
	confirm: function (content, confirmfun, cancelfun) {
		wx.showModal({
			title: '操作确认',
			content: content.toString(),
			showCancel: true,
			success: function (res) {
				if (res.confirm) {
					typeof confirmfun == 'function' && confirmfun();
				} else {
					typeof cancelfun == 'function' && cancelfun();
				}
			}
		});
	},
	success: function (title) {
		if (undefined == title) title = '操作成功';
		wx.showToast({
			title: title.toString(),
			icon: 'success'
		})
	},
	error: function (title, duration) {
		if (title === false) {
			wx.hideToast();
		} else {
			if (this.isNull(duration)) duration = 2500;
			if (undefined == title) title = '操作失败';
			wx.showToast({
				title: title.toString(),
				icon: 'none',
				duration: duration
			});
		}
	},
	showLoading: function (top) {
		this.getpage().setData({ $loadingData: { loadingVisible: true, top: top } })
	},
	hideLoading: function () {
		this.getpage().setData({ $loadingData: { loadingVisible: false } })
	},
	loading: function (title) {
		if (title === false) {
			wx.hideLoading();
		} else {
			if (undefined == title) title = '加载中';
			wx.showLoading({
				title: title.toString(),
				mask: true
			});
		}
	},
	showEmpty: function (message, image) {
		this.getpage().setData({ $dataEmpty: { visible: true, message: message, image: image } })
	},
	hideEmpty: function () {
		this.getpage().setData({ $dataEmpty: { visible: false } });
	},
	showWifiError: function () {
		var that = this.getpage();
		that.setData({ $wifiError: { visible: true } });
		that.hideLoading();
		that.loading(false)
	},
	menugoto:function(tourl, opentype){
		var $ = this
		$._goto(tourl, opentype);
	},
	goto: function (tourl, opentype){
		var $ = this
		if ($.isNull(opentype) && tourl){
			//var currentIndex = -1;
			var tablist = $.tabBarData['list'];
			if(tablist){
				for(var i=0;i<tablist.length;i++){
					if(tablist[i]['pagePath'] == tourl){
						//currentIndex = i;
						opentype = 'reLaunch';
					}
				}
			}
			//$.menuIndex = currentIndex
		}
		if(tourl.indexOf('pages/') ===0) tourl = '/'+tourl;
		$._goto(tourl, opentype);
	},
	_goto: function (tourl, opentype){
		var $ = this
		if (!tourl || tourl=='contact::' || tourl == 'share::') return;
		if(tourl.indexOf('tel::') === 0){//打电话
			tourl = tourl.slice(5)
			wx.makePhoneCall({
				phoneNumber: tourl
			})
			return;
		}
		if(tourl.indexOf('tel:') === 0){//打电话
			tourl = tourl.slice(4)
			wx.makePhoneCall({
				phoneNumber: tourl
			})
			return;
		}
		if(tourl.indexOf('url::') ===0){//外部链接
			tourl =  '/pages/index/webView?url=' + encodeURIComponent(tourl.slice(5));
		}
		if(tourl.indexOf('https://') ===0){//外部链接
			tourl =  '/pages/index/webView?url=' + encodeURIComponent(tourl);
		}
		if(tourl.indexOf('miniProgram::') ===0){//其他小程序
			tourl = tourl.slice(13);
			var tourlArr = tourl.split('|');
			//console.log(tourlArr)
			wx.navigateToMiniProgram({
				appId: tourlArr[0],
				path: tourlArr[1]?tourlArr[1]:'',
			})
			return;
		}
		//console.log(tourl)
		if(tourl == 'getmembercard::'){//领取会员卡
			$.post('coupon/getmembercardparam',{card_id:''},function(res){
				if(res.status==0){
					$.alert(res.msg);
					return;
				}
				wx.navigateToMiniProgram({
					appId: 'wxeb490c6f9b154ef9', // 固定为此appid，不可改动
					extraData: res.extraData, // 包括encrypt_card_id outer_str biz三个字段，须从step3中获得的链接中获取参数
					success: function() {},
					fail: function() {},
					complete: function() {}
				})
			})
			return;
		}
		if(tourl.indexOf('location::') ===0){//坐标导航
			tourl = tourl.slice(10);
			var tourlArr = tourl.split('|');
			var jwd = tourlArr[1].split(',');
			wx.openLocation({
				latitude:parseFloat(jwd[1]),
				longitude:parseFloat(jwd[0]),
				name:tourlArr[0],
				scale: 13
			})
			return;
		}
		
		if ($.isNull(opentype)) {
			var mv = tourl.split("?");
			var urlpath = mv[0];
			if(urlpath == $.indexurl){
				opentype = 'reLaunch';
			} else {
				opentype = $.getopentype(tourl);
			}
		}
		if (opentype == 'switchTab') {
			var args = new Object();
			var name, value;
			var url = tourl; //跳转链接
			var num = url.indexOf("?");
			if (num >= 0) {
				var urlbase = url.substr(0, num);
				var str = url.substr(num + 1); //取得所有参数
				var arr = str.split("&"); //各个参数放到数组里
				for (var i = 0; i < arr.length; i++) {
					num = arr[i].indexOf("=");
					if (num > 0) {
						name = arr[i].substring(0, num);
						value = arr[i].substr(num + 1);
						args[name] = value;
					}
				}
				wx.switchTab({
					url: urlbase,
					success: function (e) {
						var page = getCurrentPages().pop();
						if (page == undefined || page == null) return;
						page.onLoad(args);
					}
				});
			} else {
				wx.switchTab({
					url: tourl,
				});
			}
		} else if (opentype == 'redirect' || opentype == 'redirectTo') {
			wx.redirectTo({
				url: tourl
			});
		} else if (opentype == 'reLaunch') {
			wx.reLaunch({
				url: tourl
			});
		} else {
			var pages = getCurrentPages();
			if (pages.length >= 10) {
				wx.redirectTo({
					url: tourl
				});
			} else {
				wx.navigateTo({
					url: tourl
				});
			}
		}
	},
	goback: function (isreload) {
		var $ = this
		if(isreload){
			var pages = getCurrentPages();
			if (pages.length > 1) {
				var prePage = pages[pages.length - 2];
				prePage._onLoad();
			}
		}
		wx.navigateBack({fail:function(){
			$.goto($.indexurl);
		}});
	},
	getopentype: function (url) {
		var mv = url.split("?");
		var urlpath = mv[0];
		var tabBarUrls = this.config.tabBarUrls;
		if (tabBarUrls) {
			for (var i in tabBarUrls) {
				if (tabBarUrls[i] == urlpath) {
					return 'switchTab';
				}
			}
		}
		return 'navigate';
	},
	post: function (url, param, callback, loadingtype) {
		var $ = this
		var that = $.getpage();
		if (url.substring(0, 8) != 'https://') {
			url = $.config.baseurl + url;
		}
		if (url.indexOf('?') > 0) {
			url += '&aid='+$.aid+'&platform='+$.platform+'&session_id=' + $.config.session_id
		} else {
			url += '?aid='+$.aid+'&platform='+$.platform+'&session_id=' + $.config.session_id
		}
		if(loadingtype!==false){
			if ($.isNull(loadingtype)) {
				$.showLoading();
			} else  {
				$.loading(loadingtype);
			}
		}
		try{
			that.setData({ $dataEmpty: { visible: false } });
			that.setData({ $wifiError: { visible: false } });
		}catch(e){}
		wx.request({
			url: url, //仅为示例，并非真实的接口地址
			data: param,
			method: 'POST',
			//header: {'content-type': 'application/json'},
			success: function (res) {
        console.log('success',res)
				if(loadingtype!==false){
					if ($.isNull(loadingtype)) {
						$.hideLoading();
					} else{
						$.loading(false);
					}
				}
				if(res.data && res.data instanceof Object && res.data.status==-1){ //弹窗登录窗口
					//console.log(res.data)
					that.setData({needAuth:res.data.authtype,authCanClose:true});
				}else if(res.data && res.data instanceof Object && res.data.status==-10){ //管理员登录
					$.goto('/am/pages/login/index','redirect');
				}else{
					typeof callback == "function" && callback(res.data);
				}
				if(res.data && res.data instanceof Object && res.data._sysset){
					that.setData({_sysset:res.data._sysset});
				}
			},
			fail: function (res) {
				if(loadingtype!==false){
					if ($.isNull(loadingtype)){
						$.hideLoading();
					} else{
						$.loading(false);
					}
				}
				try{
				//that.setData({ $wifiError: { visible: true } });
				}catch(e){}
			}
		});
	},
	get: function (url, param, callback, loadingtype) {
		var $ = this
		var that = $.getpage();
		if (url.substring(0, 8) != 'https://') {
			url = $.config.baseurl + url;
		}
		if (url.indexOf('?') > 0) {
			url += '&aid='+$.aid+'&platform='+$.platform+'&session_id=' + $.config.session_id
		} else {
			url += '?aid='+$.aid+'&platform='+$.platform+'&session_id=' + $.config.session_id
		}
		if(loadingtype!==false){
			if ($.isNull(loadingtype)) {
				$.showLoading();
			} else  {
				$.loading(loadingtype);
			}
		}
		try{
		that.setData({ $dataEmpty: { visible: false } });
		that.setData({ $wifiError: { visible: false } });
		}catch(e){}
		wx.request({
			url: url, //仅为示例，并非真实的接口地址
			data: param,
			method: 'GET',
			//header: { 'content-type': 'application/json' },
			success: function (res) {
        console.log('success-get',res)
				if(loadingtype!==false){
					if ($.isNull(loadingtype)) {
						$.hideLoading();
					} else{
						$.loading(false);
					}
				}
				if(res.data && res.data instanceof Object && res.data.status==-1){ //没登录
					//console.log(res.data)
					that.setData({needAuth:res.data.authtype,authCanClose:true});
				}else if(res.data && res.data instanceof Object && res.data.status==-10){ //管理员登录
					$.goto('/am/pages/login/index','redirect');
				}else{
					typeof callback == "function" && callback(res.data);
				}
				if(res.data && res.data instanceof Object && res.data._sysset){
					that.setData({_sysset:res.data._sysset});
				}
			},
			fail: function () {
				if(loadingtype!==false){
					if ($.isNull(loadingtype)) {
						$.hideLoading();
					} else{
						$.loading(false);
					}
				}
				try{
				//that.setData({ $wifiError: { visible: true } });
				}catch(e){}
			}
		});
	},
	reguser: function (_options, callback) {
		var $ = this
		if (_options && _options.scene) {
			var _scenes = _options.scene.split('_');
			var _scene = _scenes[0]
			$.setCache('pid', _scene);
		} else {
			var _scene = 0
		}
		var session_id = $.config.session_id;
		if (session_id) {
			wx.checkSession({
				success: function () {
					$.post('pub/checkuser', {pid: _scene}, function (data) {
						if (data.status==0) {
							$.onLogin(_scene, callback);
						} else {
							$.mid = data.mid;
							typeof callback == 'function' && callback();
						}
						//getCurrentPages()[0].onLoad()
						//console.log(getCurrentPages()[0])
					},false)
				},
				fail: function () {
					console.log('session 登录态过期');
					$.onLogin(_scene, callback);
				}
			});
		} else {
			$.onLogin(_scene, callback);
		}
	},
	onLogin: function (_scene, callback) {
		var $ = this
		//调用登录接口
		wx.login({
			success: function (res) {
				if (res.code) {
					$.post('pub/onLogin', { code: res.code, pid: _scene }, function (res) {
						if (res.status == 0) {
							//loading(false);
							$.alert(res.msg);
						} else {
							wx.setStorageSync('session_id', res.session_id);
							$.config.session_id = res.session_id;
							if(res.status == -2){
								$.mid = 0;
							}else{
								$.mid = res.mid;
							}
							try{
								getCurrentPages()[0].onLoad();
							}catch(t){
							
							}
							typeof callback == 'function' && callback();
						}
					},false)
				} else {
					//loading(false);
					$.alert('获取用户登录态失败！' + res.errMsg);
				}
			},
			fail: function (res) {
				var that = $.getpage();
				//that.setData({ $wifiError: { visible: true } });
				that.hideLoading();
			}
		});
	},
	chooseImage: function (callback, count) {
		var $ = this;
		wx.chooseImage({
			count: count || 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: function (res) {
				//console.log(res)
				var tempFilePaths = res.tempFilePaths,
					imageUrls = [];
				for (var i = 0; i < tempFilePaths.length; i++) {
					$.loading('上传中');
					wx.uploadFile({
						url: $.config.baseurl + 'Imageupload/uploadImg/aid/'+$.aid+'/platform/'+$.platform+'/session_id/' + $.config.session_id,
						filePath: tempFilePaths[i],
						name: 'file',
						success: function (res) {
							$.loading(false);
							var data = JSON.parse(res.data);
							if (data.status == 1) {
								imageUrls.push(data.url);
								if (imageUrls.length == tempFilePaths.length) {
									typeof callback == 'function' && callback(imageUrls);
								}
							} else {
								$.alert(data.msg);
							}
						},
						fail: function (res) {
							$.loading(false);
							$.alert(res.errMsg);
						}
					});
				}
			},
			fail: function (res) {
				//alert(res.errMsg);
			}
		})
	},
	setCache: function (key, value) {
		return wx.setStorageSync(key, value);
	},
	getCache: function (key) {
		return wx.getStorageSync(key);
	},
	removeCache: function (key) {
		var $ = this;
		if ($.isNull(key)) {
			wx.clearStorageSync();
		} else {
			wx.removeStorageSync(key);
		}
	},
	_url :function(){  //获取当前页url
			var pages = getCurrentPages()    //获取加载的页面
			var currentPage = pages[pages.length - 1]    //获取当前页面的对象
			var url = '/'+ (currentPage.route ? currentPage.route : currentPage.__route__)    //当前页面url 
			return url
	},
	_fullurl:function(){
		var pages = getCurrentPages()
		var currentPage = pages[pages.length-1]
		var url = '/'+ (currentPage.route ? currentPage.route : currentPage.__route__)
		var options = currentPage.options
		var urlWithArgs = url + '?'
		for(var key in options){
				if(key == 'id' || key == 'gid' || key == 'cid'){
					var value = options[key]
					urlWithArgs += key + '=' + value + '&'
				}
		}
		urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length-1)
		return urlWithArgs
	},
  siteInfo: require('siteinfo.js')
})